<template>
  <div class="theme-switcher">
    <el-switch
      v-model="isDarkMode"
      inline-prompt
      :active-icon="Moon"
      :inactive-icon="Sunny"
      @change="handleThemeChange"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';
import { useThemeStore } from '@/store/modules/theme';
import { Moon, Sunny } from '@element-plus/icons-vue';

const themeStore = useThemeStore();

// 使用ref而不是computed，避免双向绑定可能导致的问题
const isDarkMode = ref(themeStore.theme === 'dark');

// 监听主题变化
watch(
  () => themeStore.theme,
  newTheme => {
    isDarkMode.value = newTheme === 'dark';
  }
);

// 处理主题切换
const handleThemeChange = (value: string | number | boolean) => {
  const newTheme = value ? 'dark' : 'light';
  themeStore.setTheme(newTheme);
  // 确保根元素的data-theme属性被正确设置
  document.documentElement.setAttribute('data-theme', newTheme);
};
</script>

<style lang="scss" scoped>
.theme-switcher {
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 10px;
}
</style>
